package com.payment.ktb.activity.main4;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Base64;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.flyco.animation.BaseAnimatorSet;
import com.flyco.animation.BounceEnter.BounceTopEnter;
import com.flyco.animation.FlipEnter.FlipVerticalSwingEnter;
import com.flyco.dialog.widget.base.BottomBaseDialog;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.payment.ktb.Interface.HttpCallbackListener;
import com.payment.ktb.R;
import com.payment.ktb.activity.BaseActivity;
import com.payment.ktb.activity.MainActivity;
import com.payment.ktb.adapter.AddSettleBankCardAdapter;
import com.payment.ktb.constants.Constants;
import com.payment.ktb.constants.ConstantsUser;
import com.payment.ktb.constants.HttpActions;
import com.payment.ktb.constants.HttpUrls;
import com.payment.ktb.model.BankType;
import com.payment.ktb.utils.AlertDialogUtils;
import com.payment.ktb.utils.HttpUtils;
import com.payment.ktb.utils.LogUtil;
import com.payment.ktb.utils.Md5Utils;
import com.payment.ktb.utils.PhtotUtils;
import com.payment.ktb.utils.SharedPreferencesUtils;
import com.payment.ktb.utils.ToastUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by syd on 2016/7/28.
 */
public class AddSettleBankcardActivity extends BaseActivity{

    int lastLength;
    File file = new File(Environment.getExternalStorageDirectory(), "realnameauth.png");
    private BaseAnimatorSet mBasIn;
    BankNameBottomDialog mBankNameBottomDialog;
    List<BankType> listDates;
    AddSettleBankCardAdapter adapter;
    @BindView(R.id.et_addsettlebankcard_banknum)
    EditText et_addsettlebankcard_banknum;
    @BindView(R.id.et_addsettlebankcard_cardphone)
    EditText et_addsettlebankcard_cardphone;
    @BindView(R.id.tv_addsettlebankcard_bankCode)
    TextView tv_addsettlebankcard_bankCode;
    @BindView(R.id.iv_addsettlebankcard_bankcardpic)
    ImageView iv_addsettlebankcard_bankcardpic;
    @BindView(R.id.et_addsettlebankcard_username)
    EditText et_addsettlebankcard_username;
    @BindView(R.id.tv_addsettlebankcard_bankname)
    TextView tv_addsettlebankcard_bankname;
    String timestamp = String.valueOf(new Date().getTime());
    Context thisActivity;
    String bankType;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_addsettlebankcard);
        initTitle("添结结算卡");
        ButterKnife.bind(this);
        et_addsettlebankcard_banknum.addTextChangedListener(textWatcher);
        mBasIn = new BounceTopEnter();
        mBankNameBottomDialog = new BankNameBottomDialog(mContext);
        thisActivity = this;
        initData();
    }

    private void initData() {
        et_addsettlebankcard_username.setText(SharedPreferencesUtils.getString(ConstantsUser.userAccount));
        getBankList();
    }

    @Override
    protected void onResume() {
        super.onResume();
        initView();
    }

    private void initView() {

        if (TextUtils.isEmpty(getIntent().getStringExtra("bankName"))) {
            tv_addsettlebankcard_bankCode.setText("请选择支行");
        } else {
            tv_addsettlebankcard_bankCode.setText(getIntent().getStringExtra("bankName"));
        }

        if (!TextUtils.isEmpty(getIntent().getStringExtra("cardNo"))){
            et_addsettlebankcard_banknum.setText(getIntent().getStringExtra("cardNo"));
        }
        tv_addsettlebankcard_bankname.setText(getIntent().getStringExtra("bankSimpleName"));
        bankType = getIntent().getStringExtra("bankType");


        if (!TextUtils.isEmpty(getIntent().getStringExtra("bankphone"))) {
            et_addsettlebankcard_cardphone.setText(getIntent().getStringExtra("bankphone"));
        }

    }


    @OnClick({R.id.ll_addsettlebankcard_bankCode,R.id.iv_addsettlebankcard_bankcardpic,R.id.btn_addsettlebankcard_confirm,R.id.iv_addsettlebankcard_bankcardpicexample,R.id.rl_addsettlebankcard_deletebankcardno,R.id.ll_addsettlebankcard_bankname,R.id.rl_addsettlebankcard_deletebankcardphone})
    public void clickEvent(View view) {
        Intent intent = null;
        switch (view.getId()) {

            //添加支行联行号
            case R.id.ll_addsettlebankcard_bankCode:
                if (TextUtils.isEmpty(tv_addsettlebankcard_bankname.getText().toString())) {
                    ToastUtils.showToast("请先选择银行！");
                }else {
                    intent = new Intent(mContext,BranchBankProvinceActivity.class);
                    intent.putExtra("bankType",bankType);
                    intent.putExtra("bankSimpleName",tv_addsettlebankcard_bankname.getText().toString());
                    intent.putExtra("cardNo",et_addsettlebankcard_banknum.getText().toString());
                    intent.putExtra("bankphone",et_addsettlebankcard_cardphone.getText().toString());
                    intent.putExtra("httpActionType",getIntent().getStringExtra("httpActionType"));
                    startActivity(intent);
                }
                break;

            //银行卡正面照
            case R.id.iv_addsettlebankcard_bankcardpic:
                PhtotUtils.takePhoto(this, file, 4);
                break;


            //清空姓名
            case R.id.rl_addsettlebankcard_deletebankcardno:
                et_addsettlebankcard_banknum.setText("");
                break;

            //清空手机号
            case R.id.rl_addsettlebankcard_deletebankcardphone:
                et_addsettlebankcard_cardphone.setText("");
                break;

            //弹出银行卡名称
            case R.id.ll_addsettlebankcard_bankname:
                mBankNameBottomDialog.showAnim(mBasIn).show();
                break;


            //查看实例
            case R.id.iv_addsettlebankcard_bankcardpicexample:
                intent = new Intent(mContext, ShowPhotoActivity.class);
                intent.putExtra("phototype", "3_sample");
                startActivity(intent);
                overridePendingTransition(R.anim.enter_anim, R.anim.exit_anim);
                break;

            //确认提交
            case R.id.btn_addsettlebankcard_confirm:

                if (checkPass()) {
                    submit();
                }

                break;
        }

    }

    private boolean checkPass() {

        if (TextUtils.isEmpty(et_addsettlebankcard_cardphone.getText().toString().trim().replace(" ", ""))) {
            ToastUtils.showToast("请输入预留手机号");
            return false;
        }
        if (et_addsettlebankcard_cardphone.getText().toString().trim().length() != 11) {
            ToastUtils.showToast("请输入11位手机号");
            return false;
        }

        if (TextUtils.isEmpty(et_addsettlebankcard_banknum.getText().toString().trim().replace(" ", ""))) {
            ToastUtils.showToast("请输入银行卡号");
            return false;
        }

        if (TextUtils.isEmpty(getIntent().getStringExtra("cardCode"))) {
            ToastUtils.showToast("请选择支行");
            return false;
        }

        if (TextUtils.isEmpty(SharedPreferencesUtils.getString(SharedPreferencesUtils.getString(ConstantsUser.phone) + ConstantsUser.PIC4))) {
            ToastUtils.showToast("请先上传银行卡正面照! ");
            return false;
        }
        return true;
    }


    /**
     *
     */
    private void submit() {

        progressDialogUtils.showProgress();

        //构造传输参数
        String shopBank = et_addsettlebankcard_banknum.getText().toString().trim().replace(" ","");

        //将参数放入map中
        HashMap<String, String> map = new HashMap<String,String>();

        map.put("cardNo",et_addsettlebankcard_banknum.getText().toString().trim().replace(" ", ""));
        map.put("cardCode",getIntent().getStringExtra("cardCode"));
        map.put("cardPhone",et_addsettlebankcard_cardphone.getText().toString().trim());
        map.put("cardPic", SharedPreferencesUtils.getString(SharedPreferencesUtils.getString(ConstantsUser.phone) + ConstantsUser.PIC4));


        String httpAction = "UserSettleCardBindState";
        if (!TextUtils.isEmpty(getIntent().getStringExtra("httpActionType")) && "UserSettleCardModifyState".equals(getIntent().getStringExtra("httpActionType"))) {
            httpAction = "UserSettleCardModifyState";
        } else if (!TextUtils.isEmpty(getIntent().getStringExtra("httpActionType")) && "UserSettleCardBindState".equals(getIntent().getStringExtra("httpActionType"))) {
            httpAction = "UserSettleCardBindState";
        }

        //向服务器发送请求
        HttpUtils.HttpRequestByVollery(HttpUrls.URL, httpAction, map, mQueue, new HttpCallbackListener() {
            @Override
            public void onFinish(String response) {
                progressDialogUtils.dismissProgress();
                ToastUtils.showToast("绑卡成功！");
                startActivity(MainActivity.class);
            }

            @Override
            public void onError(VolleyError volleyError) {
                progressDialogUtils.dismissProgress();
                AlertDialogUtils.showAlertDialog(mContext, volleyError.getMessage());
            }
        });

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);


        if (requestCode == 4 && resultCode == RESULT_OK) {

            // 对拍照之后的图片进行压缩。
            Bitmap bitmap = PhtotUtils.compressBySize(file.getPath(),2560, 1440);
            BitmapFactory.Options opts = new BitmapFactory.Options();
            opts.inJustDecodeBounds = true;// 不去真的解析图片，只是获取图片的头部信息，包含宽高等；
            Bitmap bitmapTemp = BitmapFactory.decodeFile(file.getPath(),opts);
            // 设置好缩放比例后，加载图片进内容；
            opts.inJustDecodeBounds = false;
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
            while (baos.toByteArray().length / 1024>200) {
                bitmap = null;
                bitmap = BitmapFactory.decodeFile(file.getPath(), opts);
                opts.inSampleSize = opts.inSampleSize + 5;
                baos.reset();//重置baos即清空baos ByteArrayOutputStream baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 80, baos);
            }


            //显示图片
            iv_addsettlebankcard_bankcardpic.setImageBitmap(bitmap);
            final Bitmap b = PhtotUtils.compressImage(bitmap);
            progressDialogUtils.showProgress("正在上传照片...");
            new Thread(new Runnable() {
                @Override
                public void run() {
                    uploadFile(b, "CardFace");
                }
            }).start();
        }

    }




    /**
     * 上传照片
     */
    private void uploadFile(Bitmap bitmap, final String type) {


        //将图片写到out中
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
        String fileBase64 = Base64.encodeToString(out.toByteArray(), 0, out.toByteArray().length, Base64.DEFAULT);
        if (out != null) {
            try {
                out.flush();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        //将图片的字节流数据加密成base64字符输出
        fileBase64 = "data:image/png;base64," + fileBase64;

        //将参数放入map中
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("fileBase64", fileBase64);
        map.put("type", type);

        //向服务器发送请求
        HttpUtils.HttpRequestByVollery(HttpUrls.URL, HttpActions.FileUploadState, map, mQueue, new HttpCallbackListener() {
            @Override
            public void onFinish(String response) {
                progressDialogUtils.dismissProgress();
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    ToastUtils.showToast("照片上传成功！");
                    SharedPreferencesUtils.putString(SharedPreferencesUtils.getString(ConstantsUser.phone) + ConstantsUser.PIC4, jsonObject.optString("httpPath"));

                } catch (JSONException e) {
                    e.printStackTrace();
                    AlertDialogUtils.showAlertDialog(mContext, getResources().getString(R.string.json_parse_error));
                }
            }

            @Override
            public void onError(VolleyError volleyError) {
                progressDialogUtils.dismissProgress();
                AlertDialogUtils.showAlertDialog(mContext, volleyError.getMessage());
            }
        });
    }





    private TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            String etValues = s.toString();

            if (!TextUtils.isEmpty(etValues) && etValues.length() >=25) {
                et_addsettlebankcard_banknum.setText(etValues.substring(0,etValues.length()-1));
                et_addsettlebankcard_banknum.setSelection(etValues.length() - 1);
            } else {
                if (lastLength < etValues.length()) {
                    etValues = clearSpace(etValues);
                    etValues = insertSpace(etValues);
                    lastLength = etValues.length();
                    et_addsettlebankcard_banknum.setText(etValues);
                    et_addsettlebankcard_banknum.setSelection(etValues.length());

                }else {
                    lastLength = etValues.length();
                }
            }


        }
        //清除卡号中的空格
        private String clearSpace(String s) {

            return  s.replace(" ","");

        }
        //插入卡号中的空格
        private String insertSpace(String s) {

            if (s.length() > 4) {
                return  s.substring(0,4) + " " + insertSpace(s.substring(4,s.length()));
            }
            return s;
        }


    };













    public void getBankList() {

        progressDialogUtils.showProgress();

        //构造传输参数
        Map<String, String> map = new HashMap<String,String>();
        map.put("timestamp",timestamp);

        //向服务器发送请求
        HttpUtils.HttpRequestByVollery(HttpUrls.URL, HttpActions.CardBankList, map, mQueue, new HttpCallbackListener() {
            @Override
            public void onFinish(String response) {
                progressDialogUtils.dismissProgress();
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    //data
                     listDates = new Gson().fromJson(jsonObject.getJSONArray("bankTypes").toString(), new TypeToken<List<BankType>>() {}.getType());
                } catch (JSONException e) {
                    e.printStackTrace();
                    AlertDialogUtils.showAlertDialog(mContext, getResources().getString(R.string.json_parse_error));
                }
            }

            @Override
            public void onError(VolleyError volleyError) {
                progressDialogUtils.dismissProgress();
                AlertDialogUtils.showAlertDialog(mContext, volleyError.getMessage());
            }
        });

    }


    class BankNameBottomDialog extends BottomBaseDialog<BankNameBottomDialog> {

       ListView lv_addsettlebankcard_bankname;
       RelativeLayout rl_addsettlebankcard_deletebankname;

        public BankNameBottomDialog(Context context, View animateView) {
            super(context, animateView);
        }

        public BankNameBottomDialog(Context context) {
            super(context);
        }

        @Override
        public View onCreateView() {
            showAnim(new FlipVerticalSwingEnter());
            dismissAnim(null);
            View inflate = View.inflate(mContext, R.layout.dialog_addsettlebankcard_bankname, null);
            lv_addsettlebankcard_bankname = (ListView) inflate.findViewById(R.id.lv_addsettlebankcard_bankname);
            rl_addsettlebankcard_deletebankname = (RelativeLayout) inflate.findViewById(R.id.rl_addsettlebankcard_deletebankname);

            //data
            //adapter
            adapter = new AddSettleBankCardAdapter(thisActivity,listDates);
            //bind
            lv_addsettlebankcard_bankname.setAdapter(adapter);

            return inflate;
        }

        @Override
        public void setUiBeforShow() {

            rl_addsettlebankcard_deletebankname.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mBankNameBottomDialog.dismiss();
                }
            });



            lv_addsettlebankcard_bankname.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    for (int j = 0; j < listDates.size(); j++) {
                        if (j == i){
                            listDates.get(j).setSelected(true);
                        }else {
                            listDates.get(j).setSelected(false);
                        }
                    }
                    adapter.notifyDataSetChanged();
                    tv_addsettlebankcard_bankname.setText(listDates.get(i).getBankName());
                    mBankNameBottomDialog.dismiss();
                    bankType = listDates.get(i).getBankType();

                }
            });
        }
    }


}
